package com.paypalpay.controller.interfaces;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.entity.common.UserboundPaymentOrder;
import com.paypalpay.external.entity.userbound.request.RequestUserInfo;
import com.paypalpay.external.entity.userbound.response.Data;
import com.paypalpay.external.entity.userbound.response.ResponseUserInfo;
import com.paypalpay.external.entity.userbound.response.UtilsInterfaces;
import com.paypalpay.service.SequenceService;
import com.paypalpay.service.UserboundPaymentOrderService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Demo 微信用户绑定，普通用户就不用绑定了，但是还是要入库
 *
 * @author lm
 * @date 2016/09/06
 */
@RestController
@Api(value = "访问商城的用户绑定接口")
public class UserBoundDeviceController {
    @Autowired
    UserboundPaymentOrderService userboundPaymentOrderService;
    @Autowired
    private SequenceService sequenceService;
    private String token = "yv8JXeTTfqyedLcU2LAqHUTKtYA4G1kz";
    private String tradeType = "";

    @CrossOrigin
    @RequestMapping(value = "/userBound", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String userBound(@RequestBody String requestStr) {

        System.out.println("requestStr请求报文是：" + requestStr);
        UtilsInterfaces utils = new UtilsInterfaces();
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        // 设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String tradeTime = df.format(new Date());

        RequestUserInfo parseObject = JSONArray.parseObject(requestStr, RequestUserInfo.class);

        com.paypalpay.external.entity.userbound.request.Data requestData = parseObject.getData();
        String requestSign = parseObject.getSign();
        System.out.println("请求的sign是：" + requestSign);
        // 取到渠道码
        String partnerCode = requestData.getPartnerCode();
        // 将请求体json转成String
        String str = JSON.toJSONString(requestData);
        // 将Str拿去计算签名
        String sign = utils.calculateSignature(str);
        System.out.println("计算的sign是：" + sign);
        // 验证签名
        if (!requestSign.equalsIgnoreCase(sign)) {
            // 签名不通过
            String jsonString = utils.publicMessage(connSeqNo, tradeTime,
                    partnerCode, token, tradeType);
            return jsonString;

        } else {
            // 签名通过的情况
            try {

                String userId = requestData.getTradeData().getUserId();
                String deviceId = requestData.getTradeData().getDeviceId();
                String deviceType = requestData.getTradeData().getDeviceType();
                String requestOrderId = requestData.getTradeData().getRequestOrderId();
                String openId = requestData.getTradeData().getOpenid();
                String receiveUserName = java.net.URLDecoder.decode(java.net.URLDecoder.decode(requestData.getTradeData().getReceiveUserName(), "utf-8"), "utf-8");
                String receiveAddress = java.net.URLDecoder.decode(java.net.URLDecoder.decode(requestData.getTradeData().getReceiveAddress(), "utf-8"), "utf-8");
                String receivePhoneNumber = requestData.getTradeData().getReceivePhoneNumber();
                String expressPrice = requestData.getTradeData().getExpressPrice();
                String expressType = requestData.getTradeData().getExpressType();
                String company = java.net.URLDecoder.decode(java.net.URLDecoder.decode(requestData.getTradeData().getCompany(), "utf-8"), "utf-8");
                String email = requestData.getTradeData().getEmail();
                System.out.println(
                        "userId是:" + userId
                                + ";deviceId是:" + deviceId
                                + ";deviceType是:" + deviceType
                                + ";requestOrderId是:" + requestOrderId
                                + ";openId是:" + openId
                                + ";receiveUserName是:" + receiveUserName
                                + ";receiveAddress是:" + receiveAddress
                                + ";receivePhoneNumber是:" + receivePhoneNumber
                                + ";expressPrice是:" + expressPrice
                                + ";expressType是:" + expressType
                                + ";company是:" + company
                                + ";email是:" + email);

                if (deviceId == null || deviceId.length() < 0 || openId == null || openId.length() < 0) {
                    // 参数不齐
                    System.out.println("参数不齐");
                    Data data = new Data();
                    data.setConnSeqNo(connSeqNo);
                    data.setPartnerCode(partnerCode);
                    data.setToken(token);
                    data.setTradeType(tradeType);
                    data.setTradeTime(tradeTime);
                    data.setTradeRstCode(1001);
                    data.setTradeRstMessage("上报参数不全");
                    // 6，给ResponsePackage赋值
                    ResponseUserInfo responseInfo = new ResponseUserInfo();
                    responseInfo.setData(data);
                    System.out.println("签名体：" + JSON.toJSONString(data));
                    responseInfo.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                    // 返回给调用者的报文
                    String jsonString = JSON.toJSONString(responseInfo);
                    System.out.println("回复的报文是：" + jsonString);
                    return jsonString;
                } else {
                    // 参数齐全
                    if (!deviceId.equals("")) {
                        // iccid不为空
                        if (!openId.equals("")) {
                            //openid也不为空
                            if (!receiveUserName.equals("") && !receiveUserName.equals("") && !expressType.equals("") && !company.equals("") && !email.equals("")) {
                                // 除了iccid，其他参数都不为空
                                // 此时就是有卡假的有卡，当成无卡购买，expressType不为空肯定是无卡购买
                                System.out.println("receiveUserName不为空，expressType不为空，但有iccid，无卡流程");
                                UserboundPaymentOrder user = new UserboundPaymentOrder();
                                user.setOpenId(openId);
                                user.setReceiveUserName(receiveUserName);
                                user.setReceiveAddress(receiveAddress);
                                user.setReceivePhoneNumber(receivePhoneNumber);
                                user.setExpressPrice(expressPrice);
                                user.setExpressType(expressType);
                                user.setCompany(company);
                                user.setEmail(email);
                                userboundPaymentOrderService.insertWeixinNoCardInfo(user);
                            } else {
                                /*
                                 * 有deviceId，其参数全部为空，就是有卡流程
                                 */
                                System.out.println("receiveUserName和expressType都为空不是扫描就肯定是有卡购买");
                                // 先判断了当前用户有购买记录
                                int c = userboundPaymentOrderService.findExistOrNot(deviceId, openId);
                                if (c > 0) {
                                    // 说明数据库已经有当前用户的记录，只用等着下单更新就行了
                                    System.out.println("有当前用户绑定记录");
                                    // 然后需要判断用户有没有下单
                                    int count = userboundPaymentOrderService.findExistOrNotByOrderId(deviceId, openId);
                                    if (count > 0) {
                                        // 如果库里面存在iccId和openId但是orderId为null，此时的意思是有绑定数据但是并没有下单信息
                                        System.out.println("此时就不用入库了！只要等着下单更新就行了！");

                                    } else {
                                        System.out.println("此时就需要入库一条用户绑定信息");

                                        UserboundPaymentOrder user = new UserboundPaymentOrder();
                                        user.setDeviceId(deviceId);
                                        user.setDeviceType(deviceType);
                                        user.setRequestOrderId(requestOrderId);
                                        user.setOpenId(openId);
                                        userboundPaymentOrderService.userBoundWeixinAccess(user);
                                    }

                                } else {
                                    System.out.println("此时是没有此用户记录就插入一条记录");
                                    // 此时确实是用户绑定
                                    UserboundPaymentOrder user = new UserboundPaymentOrder();
                                    user.setDeviceId(deviceId);
                                    user.setDeviceType(deviceType);
                                    user.setRequestOrderId(requestOrderId);
                                    user.setOpenId(openId);
                                    userboundPaymentOrderService.userBoundWeixinAccess(user);

                                }
                            }
                        } else {
                            //新版商城deviceId上来，但是openid是没有的
                            //这个时候也是要入库的，入库deviceId+userId
                            //先查一下当前用户是不是第一次绑定
                            System.out.println("H5用户访问就插入一条记录");
//                            int c = userboundPaymentOrderService.findExistNotWeixinUser(deviceId, deviceType,requestOrderId);
//                            System.out.println("这边取到的c值是：" + c);
//                            if (c <= 0) {
//                                //说明此时数据库没有这个用户，入库
//                                UserboundPaymentOrder user = new UserboundPaymentOrder();
//                                user.setDeviceId(deviceId);
//                                user.setDeviceType(deviceType);
//                                user.setRequestOrderId(requestOrderId);
//                                user.setUserId(userId);
//                                userboundPaymentOrderService.userBounNotWeixinAccess(user);
//                                System.out.println("========================H5用户访问记录插入完成！==========================");
//                            }
                        }
                        System.out.println("iccId为有效的情况!");
                        Data data = new Data();
                        data.setConnSeqNo(connSeqNo);
                        data.setPartnerCode(partnerCode);
                        data.setToken(token);
                        data.setTradeType(tradeType);
                        data.setTradeTime(tradeTime);
                        data.setTradeRstCode(1000);
                        data.setTradeRstMessage("success");
                        // 6，给ResponsePackage赋值
                        ResponseUserInfo responseInfo = new ResponseUserInfo();
                        responseInfo.setData(data);
                        System.out.println("签名体：" + JSON.toJSONString(data));
                        responseInfo.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                        // 返回给调用者的报文
                        String jsonString = JSON.toJSONString(responseInfo);
                        System.out.println("回复的报文是：" + jsonString);
                        return jsonString;

                    } else {
                        // iccid为空
                        if (!receiveAddress.equals("") && !receiveUserName.equals("") && !expressType.equals("") && !company.equals("") && !email.equals("")) {
                            // 此时用户是无卡的用户，想要购卡
                            System.out.println("iccid为空,receiveUserName和expressType都不为空，标准无卡购买流程！");

                            int i = userboundPaymentOrderService.findExistOrNotByTemorderId(receiveUserName, openId, receiveAddress);
                            if (i > 0) {
                                // 此时需要判断的是用户有没有重复绑定记录,i>0说明数据库中有空记录未绑定下单信息
                                System.out.println("i>0说明数据库中有空记录未绑定下单信息");
                            } else {
                                System.out.println("i<0说明数据库中没有空记录，那就入库绑定一下");
                                UserboundPaymentOrder user = new UserboundPaymentOrder();
                                user.setOpenId(openId);
                                user.setReceiveUserName(receiveUserName);
                                user.setReceiveAddress(receiveAddress);
                                user.setReceivePhoneNumber(receivePhoneNumber);
                                user.setExpressPrice(expressPrice);
                                user.setExpressType(expressType);
                                user.setCompany(company);
                                user.setEmail(email);
                                userboundPaymentOrderService.insertWeixinNoCardInfo(user);

                            }
                            // 无卡流程也是成功的，回复报文
                            Data data = new Data();
                            data.setConnSeqNo(connSeqNo);
                            data.setPartnerCode(partnerCode);
                            data.setToken(token);
                            data.setTradeType(tradeType);
                            data.setTradeTime(tradeTime);
                            data.setTradeRstCode(1000);
                            data.setTradeRstMessage("success");
                            // 6，给ResponsePackage赋值
                            ResponseUserInfo responseInfo = new ResponseUserInfo();
                            responseInfo.setData(data);
                            System.out.println("签名体：" + JSON.toJSONString(data));
                            responseInfo.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                            // 返回给调用者的报文
                            String jsonString = JSON.toJSONString(responseInfo);
                            System.out.println("回复的报文是：" + jsonString);
                            return jsonString;

                        } else {
                            // 此时用户既没有iccid也没有快件信息，说明上发报文不完整
                            System.out.println("既没有iccid也没有快件信息，说明上发报文不完整");
                            Data data = new Data();
                            data.setConnSeqNo(connSeqNo);
                            data.setPartnerCode(partnerCode);
                            data.setToken(token);
                            data.setTradeType(tradeType);
                            data.setTradeTime(tradeTime);
                            data.setTradeRstCode(1001);
                            data.setTradeRstMessage("无效的绑定信息");
                            // 6，给ResponsePackage赋值
                            ResponseUserInfo responseInfo = new ResponseUserInfo();
                            responseInfo.setData(data);
                            System.out.println("签名体：" + JSON.toJSONString(data));
                            responseInfo.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                            // 返回给调用者的报文
                            String jsonString = JSON.toJSONString(responseInfo);
                            System.out.println("回复的报文是：" + jsonString);
                            return jsonString;

                        }
                    }

                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
        return null;

    }
}
